<!--新增/编辑/查看-->
<template>
  <el-dialog
    v-loading.lock="loading"
    v-toggle-full
    class="base-dialog"
    :custom-class="'panna-dialog_medium'"
    :append-to-body="true"
    :title="title"
    align="center"
    :close-on-click-modal="false"
    :visible.sync="innerDialogFormVisible"
    @closed="closedDialog"
  >
    <p slot="title">{{ title }}</p>
    <el-form
      ref="formData"
      label-width="100px"
      :model="formData"
      :rules="formDataRules"
      status-icon
    >
      <el-row>
        <el-col :span="10">
          <el-form-item
            label="台账编号"
            :label-width="formLabelWidth"
            prop="num"
            :error="errorMsg.num"
          >
            <el-input v-model="formData.num" autocomplete="off"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="5">
          <el-form-item
            label="选择物料"
            :label-width="formLabelWidth"
            prop="materialId"
            :error="errorMsg.materialId"
          >
            <el-button
              icon="el-icon-plus"
              type="primary"
              @click="selectMaterial()"
              >选择</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
      <div style="margin-top: -20px; margin-bottom: 20px">
        <el-table
          :data="materialTable"
          element-loading-text="Loading"
          fit
          align="center"
          border
          highlight-current-row
          height="100px"
        >
          <el-table-column label="物料编号" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.number }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料名称" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="规格" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.size }}</span>
            </template>
          </el-table-column>
          <el-table-column label="包装单位" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.packingUnit }}</span>
            </template>
          </el-table-column>
          <el-table-column label="来源" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.source }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-row>
        <el-col :span="10">
          <el-form-item
            label="选择仓库"
            :label-width="formLabelWidth"
            prop="storageId"
            :error="errorMsg.storageId"
          >
            <el-select
              v-model="formData.storageId"
              placeholder="请选择入库仓库"
              filterable
              clearable
              @change="(val) => selectStorage(val)"
            >
              <el-option
                v-for="item in storageIdData"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="10">
          <el-form-item
            label="选择时间"
            :label-width="formLabelWidth"
            prop="selectTime"
            :error="errorMsg.selectTime"
          >
            <el-date-picker
              v-model="formData.selectTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="10">
          <el-form-item
            label="台账类型"
            :label-width="formLabelWidth"
            prop="storageId"
            :error="errorMsg.ledgerType"
          >
            <el-select
              v-model="formData.ledgerType"
              placeholder="请选择台账类型"
              filterable
              clearable
              @change="(val) => selectLedgerType(val)"
            >
              <el-option
                v-for="item in ledgerTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item
            v-if="airBottleListShow"
            label="气瓶编号"
            :label-width="formLabelWidth"
            prop="storageId"
            :error="errorMsg.sysBusinessAirBottleNum"
          >
            <el-select
              v-model="formData.sysBusinessAirBottleNum"
              placeholder="请选择气瓶编号"
              filterable
              clearable
            >
              <el-option
                v-for="item in airBottleList"
                :key="item.num"
                :label="item.num"
                :value="item.num"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 选择物料 -->
    <SelectMaterialDialog
      v-if="dialogProductVisible"
      ref="SelectMaterialDialog"
      :dialog-product-visible.sync="dialogProductVisible"
      :multiple-select-state.sync="multipleSelectState"
      @confirmSelected="confirmSelected"
    />
    <span slot="footer" class="base-dialog-footer">
      <el-button type="primary" @click="onSubmit">保 存</el-button>
      <el-button @click="cancel">取 消</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { getStorageList } from "../../../api/Material/Common.js";
import {
  GetMaterialManageLedgerNum,
  create,
} from "../../../api/Material/MaterialManageLedger";
import { getListAirBottle } from "../../../api/Material/MaterialOrderProductDetails";
import SelectMaterialDialog from "../../../components/SelectMaterialDialog.vue";
import { formatTime } from "../../../utils/time";
export default {
  name: "MaterialLedgerEdit",
  components: { SelectMaterialDialog },
  props: {
    dialogFormVisible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      ledgerTypeList: [
        { label: "普通", value: "1" },
        { label: "气瓶", value: "2" },
      ],
      airBottleListShow: false,
      airBottleList: [],
      loading: false,
      multipleSelectState: false,
      dialogProductVisible: false,
      innerDialogFormVisible: false,
      title: "生成台账",
      formLabelWidth: "100px",
      generateNum: "",
      formatTime,
      materialTable: [],
      storageIdData: [],
      formData: {
        num: "",
        materialId: "",
        storageId: "",
        storageName: "",
        selectTime: [],
        selectStartTime: null,
        selectEndTime: null,
        // true系统生成的编号
        generateNumState: true,
        ledgerType: "1",
        sysBusinessAirBottleNum: "",
      },
      errorMsg: {
        num: "",
        materialId: "",
        storageId: "",
        storageName: "",
        selectTime: "",
        ledgerType: "",
        sysBusinessAirBottleNum: "",
      },
      formDataRules: {
        num: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        materialId: [
          {
            required: true,
            trigger: "blur",
            message: "请选择数据",
          },
        ],
        storageId: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        selectTime: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
      },
    };
  },
  created() {
    this.innerDialogFormVisible = this.dialogFormVisible;
    this.init();
  },

  methods: {
    onSubmit() {
      if (this.formData.num !== this.generateNum) {
        this.formData.generateNumState = false;
      }
      this.formData.selectStartTime = this.formData.selectTime[0] + " 00:00:00";
      this.formData.selectEndTime = this.formData.selectTime[1] + " 23:59:59";

      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.loading = true;
          create(this.formData)
            .then((res) => {
              if (res.code === 200) {
                this.innerDialogFormVisible = false;
                this.$emit("update:dialogFormVisible", false);
                this.$emit("close", res.data);
              }
              this.loading = false;
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          return false;
        }
      });
    },
    selectLedgerType() {
      if (this.formData.ledgerType === "1") {
        this.formData.sysBusinessAirBottleNum = "";
        this.airBottleListShow = false;
      } else {
        if (this.formData.materialId === 0 || this.formData.materialId === "") {
          this.$message.warning("请先选择物料");
          this.formData.ledgerType = "1"
          return
        }
        this.selectAirBottleNum();
      }
    },
    selectAirBottleNum() {
      // 获取气瓶列表
      getListAirBottle({ productId: this.formData.materialId })
        .then((res) => {
          this.airBottleList = res.data;
          this.formData.sysBusinessAirBottleNum = this.airBottleList[0].num;
          this.airBottleListShow = true;
        })
        .catch((res) => {
          this.airBottleList = [];
          this.airBottleListShow = true;
        });
    },

    // 选择物料
    selectMaterial() {
      this.dialogProductVisible = true;
    },
    confirmSelected(data) {
      this.materialTable = [];
      this.materialTable.push(data);
      this.formData.materialId = data.id;
      this.formData.ledgerType = "1";
      this.formData.sysBusinessAirBottleNum = "";
      this.airBottleListShow = false;
    },
    init() {
      GetMaterialManageLedgerNum({}).then((res) => {
        this.formData.num = res.data;
        this.generateNum = res.data;
      });
      getStorageList().then((res) => {
        if (res.data.dataList?.length > 0) {
          this.storageIdData = res.data.dataList.map((item) => {
            return {
              ...item,
              value: item.id,
            };
          });
        }
      });
      this.setDefaultDateRange();
    },
    closedDialog() {
      this.cancel();
    },
    cancel() {
      this.innerDialogFormVisible = false;
      this.$emit("update:dialogFormVisible", false);
      this.$emit("close");
    },
    selectStorage(val) {
      var obj = {};
      obj = this.storageIdData.find(function(i) {
        return i.id === val;
      });
      this.formData.storageId = obj.id;
      this.formData.storageName = obj.name;
    },
    setDefaultDateRange() {
      const startDate = new Date(); // 当前时间
      startDate.setDate(1); // 设置为本月1日
      const endDate = new Date(); // 当前时间
      this.formData.selectTime = [formatTime(startDate), formatTime(endDate)];
    },
  },
};
</script>
